package exam.test11.refer;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class Bespoke {

	/*
	 * Contains information about log entries
	 * key = id, value = log object
	 */
	public Map<Integer, SimpleLog> data;

	public static void main(String[] args) {
		Bespoke b = new Bespoke();
		String delimiter = ",";

		//loading...

		b.loadData("resources/listoferrors.txt", delimiter);

		for (Map.Entry<Integer, SimpleLog> e : b.data.entrySet())
			System.out.println(e.getValue().toString());

		//saving...
		b.saveData("resources/listoferrors_1.txt", delimiter, true);
	}

	/*
	 * Save Data into PrintLinkList File
	 * @param filePath
	 * @param delimiter (comma, tab, semi-colon, ...)
	 * @param append
	 */

	//把数据从属性里写入到一个文件夹，main函数里先调用了loadData,所以data属性里已经有数据了
	public void saveData(String filePath, String delimiter, Boolean append) { //写入数据的方法，filepath指出文件的路径，也有可能直接传进来一个file， 这个delimeter是分隔符的意思，所以可以在别的方法中随便指定分隔符，不用在savedata
		//里就写好，

		//这个try后面跟括号叫，try with resource, 这个括号里面的资源会在try 语句结束之后自动释放
		try (BufferedWriter bw = new BufferedWriter(new FileWriter(filePath, append))) // 用bufferedWriter里面放一个fileWriter对象来创建一个bufferedWriter对象
		{
			/*
			 * There are many ways to write to PrintLinkList file in java. For example using FileWriter, FileOutputStream, BufferedWriter, ...
			 * BufferedWriter is very common, has PrintLinkList buffer (which is good when you have IO operations - may achieve better performance).
			 */
			for (Map.Entry<Integer, SimpleLog> e : data.entrySet()) //遍历data 属性中的每一个元素的kv parirs, 这个map 的 kv pairs 的类型就是 Map.Entry<>
			{
				SimpleLog p = e.getValue(); //data中存入的是simpleLog类的对象, 所以先要导出kv pair的 value 部分

				String record = p.toString(); //然后再调用toString方法得到string

				bw.write(record); //将得到的string写入
				bw.newLine(); //换下一行
				//bw.flush();
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void loadData(String filePath, String delimiter) {
		try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
			String record;
			this.data = new HashMap<Integer, SimpleLog>(); //初始化data属性里的map
			while ((record = br.readLine()) != null) {
				String[] tokens = record.split(delimiter); //先按照传进来的要求的分隔符把一整条string分成String[]
				int id = Integer.parseInt(tokens[0]); //把第一个string作为ID
				SimpleLog p = new SimpleLog(id, tokens[1], tokens[2], tokens[3], tokens[4], tokens[5]); //剩下的，作为smpleLog的型参，放入simpleLog对象内
				data.put(id, p);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}